import Vue from 'vue'
import VueRouter from 'vue-router'
import { tokenName } from '@/config/env.js'

import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import Welcome from '../views/Welcome.vue'
import Users from '../views/Users.vue'
import Rights from '../views/Rights.vue'
import Roles from '../views/Roles.vue'
import GoodsCates from '../views/GoodsCates.vue'
import GoodsParams from '../views/GoodsParams.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/home/welcome',
    children: [
      {
        path: 'welcome',
        component: Welcome
      },
      {
        path: 'users', // 访问url:http://localhost:8889/#/home/users ==> 子组件渲染到父组件路由占位符上，父组件渲染到根组件占位符上
        // path:'/users',// 访问: http://localhost:8889/#/users ==> 子组件渲染到父组件上，父组件渲染到根组件上; // 如果在此路由规则前定义了路由规则'/users',则会加载第一个匹配到的路由的模块
        component: Users
      },
      {
        path: 'rights',
        component: Rights
      },
      {
        path: 'roles',
        component: Roles
      },
      { path: 'categories', component: GoodsCates },
      { path: 'params', component: GoodsParams }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 设置路由守卫进行是否登录判断
router.beforeEach = (to, from, next) => {
  if (to.path === '/login') return next()
  const token = sessionStorage.getItem(tokenName)
  if (!token) return next('/login')
  next(true)
}
export default router
